#include "tim_app.h"

void Tim_set_duty(uint16_t duty)
{
    TIM2->CCR2 = (TIM2->ARR +1 )* (duty / 100.0f);
}

void Tim_set_freq(uint16_t freq)
{
    uint32_t Clock_freq = 1000000;

    uint32_t value = Clock_freq / freq - 1;

    TIM2->CCR2 = (value + 1) * (TIM2->CCR2 / (float)(TIM2->ARR + 1) );

    TIM2->ARR = value;

    TIM2->EGR = TIM_EGR_UG;
}

uint16_t duty = 10;
uint16_t freq = 4000;
void tim_proc(void)
{
    if (out_lock)
    {
        if(out_mode == 'L')
        {
            freq += 80;
            if(freq > 8000)
                freq = 8000;
        }
        else if(out_mode == 'H')
        {
            freq -= 80;
            if(freq < 4000)
                freq = 4000;
        }
        Tim_set_freq(freq);
    }
    if(!duty_lock)
    {
        Tim_set_duty(duty);
    }
}

uint32_t ic_buffer[10];
float ic_value;
uint8_t rate_clok;
uint32_t rate_time;
void tim_ic_proc(void)
{
    ic_value = 0;
    for (int i = 0; i < 10;i++)
    {
        ic_value += ic_buffer[i];
    }

    ic_value /= 10.0f;
    ic_value = 10000000.0f / ic_value;

    rate_V = (ic_value * 2 * PI * true_R) / (100.0f * true_K);



    if(out_mode == 'L')
    {
        if(rate_V > ML && !rate_clok)
        {
            rate_time = HAL_GetTick();
            rate_clok = 1;
        }
        uint32_t now_tim = HAL_GetTick();
        if (now_tim <= rate_time+2000)
        {
            if(rate_V < ML)
            {
                rate_clok = 0;
            }
        }
        else
        {
            if(rate_V > ML)
            {   
                ML = rate_V;
                rate_clok = 0;   
            }

        }
    }
    else if(out_mode == 'H')
    {
        if (rate_V > MH && !rate_clok)
        {
            rate_time = HAL_GetTick();
            rate_clok = 1;
        }
        uint32_t now_tim = HAL_GetTick();
        if (now_tim <= rate_time + 2000)
        {
            if (rate_V < MH)
            {
                rate_clok = 0;
            }
        }
        else
        {
            if (rate_V > MH)
            {
                MH = rate_V;
                rate_clok = 0;
            }
        }
    }
}
